const util = require('../../utils/util')
const nowDate = new Date()
let p

Page({

	data: {
		_nowWeek: 1,
		nowWeek: 1,
		nowTime: nowDate.getHours() + '' + (nowDate.getMinutes().toString().length == 1 ? '0' + nowDate.getMinutes() : nowDate.getMinutes()),
		nowDay: nowDate.getDay() == 0 ? 7 : nowDate.getDay(),
		courseStartDate: {
			month: 1,
			day: 8
		},
		syllabusDate: [],
		syllanusTime: [],
		syllabusList: [],
		courseInfo: false,
		loadingPanel: {
			tip: '同步中'
		}
	},

	temp: {
		syllabusData: {},
		syncingSyllabus: false
	},

	onLoad: function (params) {
		p = this
		if (!params.stuId)
			wx.navigateBack()
		p.temp.stuId = params.stuId
		p.syncSyllabus(false, p.temp.stuId)
	},

	onUnload: () => {
		util.unloadPage('otherSyllabus')
	},

	onShow: () => {
		if (p.data.syllabusList.length == 0)
			p.syncSyllabus(false, p.temp.stuId)
	},

	syncSyllabus: (updateSyllabus = false, stuId) => {
		p.getSyllabus({
			stuId,
			updateSyllabus,
			success: (syllabusData) => {
				console.log(syllabusData)
				p.loadSyllabus({
					syllabusData,
					success: () => {
						util.iconBox('success', '同步成功')
					},
					fail: (code, msg) => {
						util.error('加载课程表失败', util.errorHandler(code, msg))
					}
				})
			},
			fail: (code, msg) => {
				util.error('同步对方课程表失败', util.errorHandler(code, msg))
			}
		})
	},

	getSyllabus: (obj) => {
		const { success, fail, stuId, updateSyllabus } = obj
		if (p.temp.syncingSyllabus)
			return
		p.temp.syncingSyllabus = true
		util.request({
			source: 'otherSyllabus',
			method: updateSyllabus ? 'put' : 'get',
			uri: `user/student/${stuId}/correl/syllabus`,
			data: {
				session: util.globalData('session')
			},
			success: (data) => {
				if (util.isString(data.stuSyllabus))
					data.stuSyllabus = JSON.parse(data.stuSyllabus)
				success(data)
			},
			fail: (code, msg) => {
				if (code == '-2063')
					p.syncSyllabus(true, p.temp.stuId)
				else {
					util.hideLoadingPanel(p)
					p.temp.syncingSyllabus = false
					fail(code, msg)
				}
			}
		})
	},

	loadSyllabus: (obj) => {
		try {
			const { syllabusData, success, fail } = obj
			let syllabusList = []
			const { stuCourseTime, stuSyllabus, stuSyllabusList } = syllabusData
			const { courseYear, courseTerm, courseTime, courseStartDate, courseEndDate } = stuCourseTime
			const that = p
			let nowWeek = parseInt((util.timestamp() - courseStartDate) / 86400 / 7) + 1
			if (!stuSyllabusList) {
				p.temp.syllabusData = syllabusData
				let maxWeek = parseInt((courseEndDate - courseStartDate) / 86400 / 7)
				for (let w = 0; w < maxWeek; w++) {
					for (let d = 0; d < 7; d++) {
						for (let p = 0; p < 10; p++) {
							if (!syllabusList[w]) {
								syllabusList[w] = []
							}
							if (!syllabusList[w][d]) {
								syllabusList[w][d] = []
							}
							else if (!syllabusList[w][d][p]) {
								syllabusList[w][d][p] = {}
							}
							if (!stuSyllabus[d + 1] || !stuSyllabus[d + 1][(p + 1) * 2])
								continue
							let conflictTexts = []
							let conflictList = []
							const courses = stuSyllabus[d + 1][(p + 1) * 2]
							for (let index in courses) {
								const { color, name, room, tchs, time } = courses[index]
								const { sw, ew, dw } = time
								const nw = w + 1
								if (nw >= sw && nw <= ew && (dw == -1 || dw == 0 && nw % 2 != 0 || dw == 1 && nw % 2 == 0)) {
									conflictTexts.push(`${name} ${room} ${tchs.join('、')}`)
									conflictList.push({ w, d, p, color, room, tchs })
									syllabusList[w][d][p] = { color, name, room, tchs }
								}
							}
							if (conflictList.length > 1 && (w + 1) >= nowWeek) {
								wx.showModal({
									title: '课程冲突处理',
									content: `系统检测到此课表第${w + 1}周星期${d + 1}的第${(p + 1) * 2}节课有${conflictList.length}门课发生冲突，点击确定后选择需要显示在课程表上的课程，也可以点击“自动处理”系统将自动显示冲突课程中的最后一门课`,
									confirmColor: '#ff6759',
									confirmText: '手动选择',
									cancelText: '自动处理',
									success: (res) => {
										if(res.confirm) {
											wx.showActionSheet({
												itemList: conflictTexts,
												success: (res) => {
													if(res.cancel) {
														util.modal('系统提示', '您取消了课程冲突处理，已为您自动处理，如果需要重新处理冲突可以下拉刷新课程表同步后处理')
														return
													}
													const c = conflictList[res.tapIndex]
													syllabusList[c.w][c.d][c.p] = {
														color: c.color,
														name: conflictTexts[res.tapIndex],
														room: c.room,
														tchs: c.tchs
													}
													that.setData({
														syllabusList
													})
												}
											})
										}
									}
								})
							}
						}
					}
				}
			}
			else
				syllabusList = stuSyllabusList
			//如果当前周大于课程表最大周数则使用最后一周课程表数据
			if (nowWeek > syllabusList.length)
				nowWeek = syllabusList.length
			p.setData({
				nowWeek,
				_nowWeek: nowWeek,
				syllabusStartTime: courseStartDate,
				syllanusTime: courseTime.split(','),
				syllabusList
			})
			wx.setNavigationBarTitle({
				title: `第${nowWeek}周`,
			})
		}
		catch(err) {
			console.error(err)
			util.error('加载失败', '无法加载课程表数据，请下拉刷新重试')
		}
		util.hideLoadingPanel(p)
		p.temp.syncingSyllabus = false
	},

	changeSyllabusWeek: (e) => {
		const week = e.detail.current + 1
		p.setData({
			nowWeek: week,
			termPanelOpened: false
		})
		wx.setNavigationBarTitle({
			title: `第${week}周`,
		})
	},

	showCourseInfo: (e) => {
		const {day, pitch} = e.currentTarget.dataset
		const course = p.data.syllabusList[p.data.nowWeek - 1][day][pitch]
		if (!course || !course.name)
			return
		const { color, name, room, tchs } = course
		p.setData({
			courseInfo: { color, name, room, tchs, pitch: (pitch * 2 + 1) + '-' + (pitch * 2 + 2) }
		})
	},

	hideCourseInfo: () => {
		p.setData({
			courseInfo: false
		})
	},

	onPullDownRefresh: () => {
		wx.showModal({
			title: '操作提示',
			content: '下拉刷新将会同步学校教务系统的最新课表到服务器和本地并更新课程的颜色，请问是否需要同步最新课表？',
			success: (res) => {
				if(res.confirm) {
					util.showLoadingPanel(p, '同步中')
					p.syncSyllabus(true, p.temp.stuId)
				}
				wx.stopPullDownRefresh()
			}
		})
	}

})